#include "StdAfx.h"
#include "UserMgr.h"
#include "dao/userDao.h"
#include "dao/DAOFactory.h"
#include <algorithm>


CUserMgr::CUserMgr(void):m_bInit(false)
{

	m_userDao = CDAOFactory::GetUserDao();

}

CUserMgr::~CUserMgr(void)
{

	if(m_userDao)
		delete m_userDao;
}



BOOL  CUserMgr::AddAUser(CUser*pUser)
{
	bool bOk;
	if(pUser == NULL)
		return false;

	do 
	{

		if(!m_userDao->AddAUser(*pUser))
		{	
			bOk= false;
			delete pUser;
			break;
		}
		m_userInfoVector.push_back(pUser);
		bOk = true;
	} while (false);


	return bOk;
		
}

BOOL  CUserMgr::ModifyAUser(CUser* pUser)
{
	bool bOk;
	if(pUser == NULL)
		return false;

	do 
	{
		if(m_userDao == NULL)
			break;
		if(m_userDao->ModifyPassword(*pUser))
		{
			bOk = true;
			break;
		}

	} while (0);



	return bOk;
}

BOOL CUserMgr::DelAUser(CUser*pUser)
{

	if(pUser == NULL)
		return false;

	bool bOk= false;

	vector<CUser*>::iterator  it;
	do 
	{
		if(!m_userDao->DelAUser(pUser->m_userName))
		{
			break;
		}

		for(it = m_userInfoVector.begin();it != m_userInfoVector.end();it++)
		{
			if((*it )== pUser )
			{
				m_userInfoVector.erase(it);
				break;
			}
		}

		delete pUser;
		bOk = true;

	} while (FALSE);

	return bOk;
}



void CUserMgr::LoadUserInfo()
{
	CUser      *user;

	if(m_bInit)
		return;
	do 
	{
		if(!m_userDao->GetAllUser())
		{
			break;
		}
		user = new CUser;
		while(m_userDao->EnumUser(*user))
		{
			m_userInfoVector.push_back(user);
			user = new CUser;
		}
		if(user)
			delete user;

	} while (FALSE);

	m_bInit = true;


}

bool   CUserMgr::DoLogin(CUser&   user)
{
	bool bOk = false;

	if(user.m_userName == "" || user.m_pwd == "")
		return false;
	do 
	{

		if(m_userDao->IsLegalUser(user))
		{
			bOk = true;
			break;
		}

	} while (0);

	return bOk;
}





BOOL CUserMgr::IsUserExist(CString& userName)
{
	UserFinder  userFinder;
	userFinder.userName = userName;
	vector<CUser*>::iterator it;
	if(!m_bInit)
		LoadUserInfo();
	it = std::find_if(m_userInfoVector.begin(),m_userInfoVector.end(),userFinder);
	if(it != m_userInfoVector.end())
		return true;
	return false;
}


void CUserMgr::Clear()
{
	CUser*  pUser = NULL;
	while(m_userInfoVector.size())
	{
		pUser = m_userInfoVector.back();
		m_userInfoVector.pop_back();
		if(pUser)
			delete  pUser;
	}
	m_bInit = false;
}